import Map from 'ol/Map'
import View from 'ol/View'
import Layer from 'ol/layer/Layer' // 瓦片加载器
import TileLayer from 'ol/layer/Tile'
import { XYZ } from 'ol/source.js'

import { get } from 'ol/proj'
import { TileWMS } from 'ol/source'
import VectorImageLayer from 'ol/layer/VectorImage.js'
import { createFlashingPoint,createPointImg } from '@/views/gis/api/gis2d/maputils'
import VectorSource from 'ol/source/Vector'
import GeoJSON from 'ol/format/GeoJSON'
import * as onemap from '@/views/gis/api/onemap'
import { Circle, Fill, Icon, Stroke, Style, Text } from 'ol/style.js'
import { fromLonLat, toLonLat, transform, transformExtent } from 'ol/proj'
import config from '@/views/gis/config/index.js'
import {get2dColor,projection,init4490} from '@/views/gis/api/gis2d/maputils'
let map
//
//地图
const initMap = (el, eqinfo, version) => {
  const projection = get('EPSG:3857')
  const tdtLayer = new TileLayer({
    id: 'ditu-layer',
    source: new XYZ({
      projection: projection,
      url: `http://t3.tianditu.com/DataServer?T=img_w&tk=${config.TDTTK}&x={x}&y={y}&l={z}`,
      crossOrigin: 'anonymous',
      wrapX: false
    })
  })

  const tdtVec = new TileLayer({
    id: 'ditu-vec',
    source: new XYZ({
      url: `http://t4.tianditu.com/DataServer?T=cva_w&tk=${config.TDTTK}&x={x}&y={y}&l={z}`,
      crossOrigin: 'anonymous',
      wrapX: false
    })
  })

  let map = new Map({
    target: el,
    layers: [tdtLayer, tdtVec],
    view: new View({
      center: transform([eqinfo.longitude, eqinfo.latitude], 'EPSG:4326', 'EPSG:3857'),
      zoom: 9
    }),
    controls: []
  })
  // addMapLayer(eqinfo.earthquakeId)
  // loadEarthQuakeYXC(eqinfo.id, 'xyc', map,version)
  //添加中性点
   init4490()
   createPointImg([eqinfo.longitude, eqinfo.latitude],'/static/assets/3d/zz.png', map)
 addRecentCityLayer(eqinfo.id,map)
  return map
}

//地图
const initMaps = (el) => {
  
  const projection = get('EPSG:3857')
  const tdtLayer = new TileLayer({
    id: 'ditu-layer',
    source: new XYZ({
      projection: projection,
      url: `http://t3.tianditu.com/DataServer?T=img_w&tk=${config.TDTTK}&x={x}&y={y}&l={z}`,
      crossOrigin: 'anonymous',
      wrapX: false
    })
  })

  const tdtVec = new TileLayer({
    id: 'ditu-vec',
    source: new XYZ({
      url: `http://t4.tianditu.com/DataServer?T=cva_w&tk=${config.TDTTK}&x={x}&y={y}&l={z}`,
      crossOrigin: 'anonymous',
      wrapX: false
    })
  })
  map = new Map({
    target: el,
    layers: [tdtLayer, tdtVec],
    view: new View({
      center: transform([116, 26], 'EPSG:4326', 'EPSG:3857'),
      zoom: 9
    }),
    controls: []
  })
  return map
}

const addMapLayer = (id) => {
  //添加地震影响场的面和中心点
  //0.4:->setting_seismic_influenceflied_mian@dzyjzhjspt_proper_guojia
  const supermaplayer = new TileLayer({
    zIndex: 10,
    source: new TileWMS({
      url: 'http://10.13.155.199:8090/iserver/services/map-dzyjzhjsptCommon-2/wms111/dzyjzhjspt_proper_guojia',

      params: {
        // LAYERS: 'setting_seismic_influenceflied_mian@dzyjzhjspt_proper_guojia',
        LAYERS: '0.4',
        FORMAT: 'image/png',
        layerDefs: JSON.stringify({
          0.4: `earth_quake_id = ${id} `
        })
      },
      serverType: 'geoserver', // 服务器类型，例如 geoserver
      crossOrigin: 'anonymous' // 跨域请求设置
    })
  })
  // const supermaplayer = new TileLayer({
  //   zIndex:10,
  //   source: new TileWMS({
  //      url: 'http://10.13.155.199:8090/iserver/services/map-dzyjzhjsptCommon/wms111/dzyjzhjspt_proper_guojia',

  //     params: {
  //       LAYERS: 'setting_seismic_influenceflied_xian@dzyjzhjspt_proper_guojia,setting_seismic_influenceflied_mian@dzyjzhjspt_proper_guojia',
  //       FORMAT: 'image/png',
  //       CQL_FILTER: "earth_quake_id=624"// CQL 过滤条件
  //     },
  //     serverType: 'geoserver', // 服务器类型，例如 geoserver
  //     crossOrigin: 'anonymous' // 跨域请求设置
  //   }),
  // })
  map.addLayer(supermaplayer)
  //设定中心点
}
let EarthQuakeYXC = {} //在线地图影响场
function loadEarthQuakeYXC(id, laycode, map, version) {
  if (EarthQuakeYXC[laycode]) {
    map.removeLayer(EarthQuakeYXC[laycode])
  }
  var query = {
    tableName: 'setting_seismic_influenceflied',
    fields:
      'uuid,earthquake_level,dz_intensity,data_source,remark,earth_quake_id,operate_time,trigger_type,model_id,category,operate_user_id,operate_dept_id,version,type,code,angle,intensity_show,intensity_china_show,area',
    filter: `earth_quake_id='${id}' AND version='${version}' `
  }
  onemap.listGeoJsonByTable(query).then((res) => {
    var geojson = JSON.parse(res.geodata.value)
    if(!geojson.features) return 
    
    var tmpLayer = new VectorImageLayer({
      declutter: true
    })
    const vectorSource = new VectorSource({
      features: new GeoJSON().readFeatures(geojson).filter(e=>e.values_.dz_intensity > 5)
    })
    tmpLayer.setSource(vectorSource)
    vectorSource.forEachFeature((feature) => {
    
      let style = new Style({
        fill: new Fill({
          color: get2dColor(feature.values_.dz_intensity)
        }),
        stroke: new Stroke({
          color: 'rgba(197, 208, 218, 0.8)',
          width: 2
        })
      })
      feature.setStyle(style)
    })
    map.addLayer(tmpLayer)
    EarthQuakeYXC[laycode] = tmpLayer

    map.getView().fit(tmpLayer.getSource().getExtent(), {
      padding: [50, 50, 50, 50], // 可选的填充，以确保要素不会被地图边缘截断
      duration: 1000 // 动画持续时间（以毫秒为单位）
    })
  })
}

//在线地图影像场
export const addYXCLayer = (eqid,version,map) => {
  
  var xycurl = "setting_seismic_influenceflied_mian__proper_guojia"
    const supermaplayer = new TileLayer({
      zIndex: 9,
      source: new TileWMS({
        id:xycurl,
        url: config.SUPERMAPURL + xycurl,
        projection: projection,
        params:{
          LAYERS: xycurl,
          FORMAT: 'image/png',
          layerDefs: JSON.stringify({
            ['0.2']: `earth_quake_id='${eqid}' AND version='${version}'`,
            ['0.1']: `earth_quake_id='${eqid}' AND version='${version}'`,
            ['0.0']: `earth_quake_id='${eqid}' AND version='${version}'` ,
          })
        },
        crossOrigin: 'anonymous', // 跨域请求设置
      })
    })
    
    map.addLayer(supermaplayer)
    return supermaplayer

}
//在线地图加载震中距
const addRecentCityLayer = (eqid,map) => {
  var layurl = ['gis_distancepoint_common','gis_distanceline_common']
  var local = sessionStorage.getItem("sysmapconfig");
  if(local){
    var a = JSON.parse(local).zzjurl;
    layurl = a.split(',')
  }
  
  const params = {
    LAYERS: '0.0',
    FORMAT: 'image/png',
    layerDefs: JSON.stringify({
      ['0.0']: `earthquake_id='${eqid}' `
    })
  }

  for (const element of layurl) {
     params.LAYERS = element
    //  if(element == layurl[0]){
    //   params.LAYERS = "0.1,0.0"
    //  }
    // params.LAYERS = "0.0,0.1"
    if(element === layurl[1]){
      params.layerDefs = JSON.stringify({
        ['0.0']: `earthquake_id='${eqid}'`,
        ['0.1']: `earthquake_id='${eqid}'`,
      })
    }

    const supermaplayer = new TileLayer({
      zIndex: 999,
      source: new TileWMS({
        id:element,
        url: config.SUPERMAPURL + element,
        projection: projection,
        params:params,
        crossOrigin: 'anonymous', // 跨域请求设置
      })
    })
  
    map.addLayer(supermaplayer)
  }


}


const delMapLayer = (laycode) => {
  const layers = map.getLayers().getArray()
  layers.forEach((layer, index) => {
    if (layer.get('id') === laycode) {
      // 替换为你的图层名称
      map.getLayers().removeAt(index) // 使用 removeAt 方法根据索引删除图层
    }
  })
}

const XZQH = {}; //区域文件
function loadAreaGeoJson(id, queryTemp) {
  var query
  if (queryTemp) {
    query = {
      tableName: queryTemp.tableName,
      fields: queryTemp.fields,
      filter: `p_id='${id}'`,
      ...queryTemp
    }
  } else {
    query = {
      tableName: 'res_level_region_sub',
      fields: 'id,p_id,province,city',
      filter: `p_id='${id}'`
    }
  }

  onemap.listGeoJsonByTable(query).then((res) => {

    var geojson = JSON.parse(res.geodata.value)
    if (!geojson.features) return;
    var tmpLayer = new VectorImageLayer({
      declutter: true
    })
    const vectorSource = new VectorSource({
      features: new GeoJSON().readFeatures(geojson)
    })

    tmpLayer.setSource(vectorSource)
    vectorSource.forEachFeature((feature) => {
      let style = new Style({
        fill: new Fill({
          color: get2dColor(6)
        }),
        stroke: new Stroke({
          color: 'rgba(197, 208, 218, 0.8)',
          width: 2
        })
      })
      feature.setStyle(style)
    })
    map.addLayer(tmpLayer)
    XZQH[id] = tmpLayer
    // console.log(EarthQuakeYXC[laycode])

    map.getView().fit(tmpLayer.getSource().getExtent(), {
      padding: [50, 50, 50, 50], // 可选的填充，以确保要素不会被地图边缘截断
      duration: 1000 // 动画持续时间（以毫秒为单位）
    })
  })
}

function loadTempAreaGeoJson(id, queryTemp) {
  var query
  if (queryTemp) {
    query = {
      tableName: queryTemp.tableName,
      fields: queryTemp.fields,
      filter: `id='${id}'`,
      ...queryTemp
    }
  } else {
    query = {
      tableName: 'temp_file_data',
      fields: 'id',
      filter: `id='${id}'`
    }
  }
  onemap.listGeoJsonByTable(query).then((res) => {

    var geojson = JSON.parse(res.geodata.value);
    if (!geojson.features) return;
    var tmpLayer = new VectorImageLayer({
      declutter: true
    })
    const vectorSource = new VectorSource({
      features: new GeoJSON().readFeatures(geojson)
    })

    tmpLayer.setSource(vectorSource)
    vectorSource.forEachFeature((feature) => {
      let style = new Style({
        fill: new Fill({
          color: get2dColor(6)
        }),
        stroke: new Stroke({
          color: 'rgba(197, 208, 218, 0.8)',
          width: 2
        })
      })
      feature.setStyle(style)
   
    })
    map.addLayer(tmpLayer)
    XZQH[id] = tmpLayer
    // console.log(EarthQuakeYXC[laycode])
    map.getView().fit(tmpLayer.getSource().getExtent(), {
      padding: [50, 50, 50, 50], // 可选的填充，以确保要素不会被地图边缘截断
      duration: 1000 // 动画持续时间（以毫秒为单位）
    })
  })
}

function delAreaGeoJson(id) {
  if (XZQH[id]) {
    map.removeLayer(XZQH[id]);
  }
}

function clearAllAreaGeoJson() {
  for (const key in XZQH) {
    map.removeLayer(XZQH[key]);
  }
}


//加载省或者县行政区划
function loadXZQHGeoJson(code,isProvince) {
  clearAllAreaGeoJson();
  if(isProvince === 1){
    var query = {
      tableName: 'district_boundary',
      fields: 'id',
      filter: `id='1'`,
      owner:"public"
    }
  }
  if( isProvince === 2){
    var query = {
      tableName: 'data_province',
      fields: 'id,enti_id,code,name,file_id',
      filter: `code=${code}`,
      owner:"public"
    }
  }
  if( isProvince === 3){ 
    var query = {
      tableName: 'data_city',
      fields: 'id,code,name,all_name,belong_province,phone_code,bz,file_id',
      filter: `code=${code}`,
      owner:"public"
    }
  }

  onemap.listGeoJsonByTable(query).then((res) => {
    var geojson = JSON.parse(res.geodata.value)
    if (!geojson.features) return;
    var tmpLayer = new VectorImageLayer({
      declutter: true
    })
    const vectorSource = new VectorSource({
      features: new GeoJSON().readFeatures(geojson)
    })

    tmpLayer.setSource(vectorSource)
    vectorSource.forEachFeature((feature) => {
      let style = new Style({
        fill: new Fill({
          color: get2dColor(6)
        }),
        stroke: new Stroke({
          color: 'rgba(197, 208, 218, 0.8)',
          width: 2
        })
      })
      feature.setStyle(style)
    })
    map.addLayer(tmpLayer)
    XZQH[code] = tmpLayer
    // console.log(EarthQuakeYXC[laycode])
  console.log(map);
  
    map.getView().fit(tmpLayer.getSource().getExtent(), {
      padding: [50, 50, 50, 50], // 可选的填充，以确保要素不会被地图边缘截断
      duration: 1000 // 动画持续时间（以毫秒为单位）
    })
  })
}


function viewerMapLayer(id) {
  clearAllAreaGeoJson()
  var query = {
    tableName: 'res_level_region_sub',
    fields: 'id,p_id,province,city',
    filter: `id='${id}'`
  }
  onemap.listGeoJsonByTable(query).then((res) => {

    var geojson = JSON.parse(res.geodata.value)
    var tmpLayer = new VectorImageLayer({
      declutter: true
    })
    const vectorSource = new VectorSource({
      features: new GeoJSON().readFeatures(geojson)
    })

    tmpLayer.setSource(vectorSource)
    vectorSource.forEachFeature((feature) => {
      let style = new Style({
        fill: new Fill({
          color: 'rgba(254, 229, 230, 0.5)'
        }),
        stroke: new Stroke({
          color: 'rgba(0, 0, 0, 1)',
          width: 1
        })
      })
      feature.setStyle(style)
    })
    map.addLayer(tmpLayer)
    // EarthQuakeYXC[laycode] = tmpLayer
    // console.log(EarthQuakeYXC[laycode])

    map.getView().fit(tmpLayer.getSource().getExtent(), {
      padding: [50, 50, 50, 50], // 可选的填充，以确保要素不会被地图边缘截断
      duration: 1000 // 动画持续时间（以毫秒为单位）
    })
  })
}

export { initMap,loadXZQHGeoJson, loadEarthQuakeYXC, initMaps, loadAreaGeoJson, clearAllAreaGeoJson, loadTempAreaGeoJson }
